package com.emm.yixun.website.controller.system;
//框架包
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.common.model.MerchantDataAuthority;
import com.emm.yixun.common.model.Resources;
//变化的引用
import com.emm.yixun.common.model.Role;
import com.emm.yixun.common.model.RoleDataAuthority;
import com.emm.yixun.common.model.RoleResources;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.MerchantDataAuthorityDto;
import com.emm.yixun.common.model.dto.RoleDataAuthorityDto;
import com.emm.yixun.common.model.dto.RoleDto;
import com.emm.yixun.common.model.dto.RoleResourcesDto;
import com.emm.yixun.common.model.dto.UserResourcesDto;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.system.service.MerchantDataAuthorityServiceFacade;
import com.emm.yixun.system.service.RoleDataAuthorityServiceFacade;
import com.emm.yixun.system.service.RoleResourcesServiceFacade;
import com.emm.yixun.system.service.RoleServiceFacade;
import com.emm.yixun.system.service.UserTokenServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.common.utils.tree.entity.ZNodes;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.system.DataAuthorityVo;
import com.emm.yixun.website.vo.system.PermissionAssignmentVo;



@Controller
@RequestMapping("/system/role/")
public class RoleController extends BaseController<Role>{
	
	@Autowired
	private RoleServiceFacade roleServiceFacade;
	@Autowired
	private RoleResourcesServiceFacade roleResourcesServiceFacade;
	@Autowired
	private MerchantDataAuthorityServiceFacade merchantDataAuthorityServiceFacade;
	@Autowired
	private RoleDataAuthorityServiceFacade roleDataAuthorityServiceFacade;
	@Autowired
	private UserTokenServiceFacade userTokenServiceFacade;
	
	private final String[] appResources={"menu_0100","menu_0104"};
	
	@RequestMapping(value="index")
	public String index(ModelMap map, HttpServletRequest request){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			List<Resources> resources= getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
			map.put("permitBtn", resources);
			map.put("permitBtnList", JSONArray.fromObject(resources));
			map.put("menu", request.getParameter("menu"));
			return "/system/role/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(RoleDto dto){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:role:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setDelFlag("0");
        		dto.setSort("0");
        		dto.setUpdateUserId(user.getId());
        		dto.setUpdateTime(new Date());
				Response<RoleDto> response=roleServiceFacade.save(dto);
				if(response.isSuccess()){
					//默认app资源：首页和我的
					for(String resources : appResources){
						RoleResourcesDto urd=new RoleResourcesDto();
						urd.setRoleId(Long.valueOf(response.getEntity().getId()));
						urd.setMerchantId(user.getMerchantId());
						urd.setResourcesCode(resources);
						urd.setCreateUserId(user.getId());
						urd.setUpdateTime(new Date());
						urd.setDelFlag("0");
						roleResourcesServiceFacade.save(urd);
					}
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:role:view"))){
        	try {
				Response<Role> response=roleServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(RoleDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:role:edit"))){
        	try {
        		Response<Integer> response=roleServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:role:delete"))){
        	try {
        		Response<Integer> response=roleServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(RoleDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:role:list"))){
        	try {
        		User user = ShiroUtil.getCurrentUser();
        		dto.setPermissionUserId(user.getId());
        		
        		//角色数据权限资源缓存
        		String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
        		if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
        			dto.setResourcesCode(resourcesCode);
        		}else if("".equals(resourcesCode)){
        			ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
        		}
        		dto.setMerchantId(user.getMerchantId());
        		
        		Page<Role> response=roleServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                	if(StringUtils.isNotEmpty(response.getErrorMsg())){
                		ar.setResMsg(response.getErrorMsg());
                	}
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//分页查询
	@RequestMapping(value="listAll", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  listAll(RoleDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
    	try {
    		User user = ShiroUtil.getCurrentUser();
    		dto.setMerchantId(user.getMerchantId());
    		ResponseList<Role> response=roleServiceFacade.findByDto(dto);
            if(response.isSuccess()){
            	if(null==response.getEntity())response.setEntity(new ArrayList<Role>());
            	ar.setSucceed(response.getEntity());
            }else{
            	ar.setFailMsg(Const.DATA_FAIL);
            }
		} catch (Exception e) {
			logger.error(e.toString(),e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
    	return ar;
    }
	
	//查询系统资源
	@RequestMapping(value="listAuthorized", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes listAuthorized(String roleId){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:role:listAuthorized"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
    			PermissionAssignmentVo permissionAssignmentVo=new PermissionAssignmentVo();
    			permissionAssignmentVo.setFunctionPoints(getFunctionPoints(user,roleId));
    			permissionAssignmentVo.setDataAuthoritys(getDataAuthoritys(user,roleId));
    			ar.setSucceed(permissionAssignmentVo);
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
	}
	
	private List<DataAuthorityVo> getDataAuthoritys(User user,String roleId){
		List<DataAuthorityVo> list=new ArrayList<DataAuthorityVo>();
		MerchantDataAuthorityDto merchantDataAuthorityDto=new MerchantDataAuthorityDto();
		merchantDataAuthorityDto.setMerchantId(user.getMerchantId());
		ResponseList<MerchantDataAuthority> mdaResponseList=merchantDataAuthorityServiceFacade.findByDto(merchantDataAuthorityDto);
		if(!mdaResponseList.isSuccess() || null==mdaResponseList.getEntity())return list;
		//数据权限选项
		List<MerchantDataAuthority> mdaList=mdaResponseList.getEntity()==null?new ArrayList<MerchantDataAuthority>():mdaResponseList.getEntity();
		RoleDataAuthorityDto roleResourcesDto=new RoleDataAuthorityDto();
		roleResourcesDto.setMerchantId(user.getMerchantId());
		roleResourcesDto.setRoleId(Long.valueOf(roleId));
		ResponseList<RoleDataAuthority> rdaResponseList=roleDataAuthorityServiceFacade.findByDto(roleResourcesDto);
		if(!mdaResponseList.isSuccess())return list;
		//已拥有数据权限
		List<RoleDataAuthority> rdaList=rdaResponseList.getEntity()==null?new ArrayList<RoleDataAuthority>():rdaResponseList.getEntity();
		
		//组装显示对象
		for(MerchantDataAuthority mda : mdaList){
			DataAuthorityVo dataAuthorityVo=new DataAuthorityVo();
			try {
				BeanUtils.copyProperties(dataAuthorityVo, mda);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String value="";
			for(RoleDataAuthority rda : rdaList){
				if(rda.getResourcesCode().equals(mda.getResourcesCode())){
					value=rda.getAuthorityValue();
					break;
				}
			}
			dataAuthorityVo.setValue(value);
			list.add(dataAuthorityVo);
		}
		return list;
	}
	
	private List<ZNodes> getFunctionPoints(User user,String roleId){
		//查询功能权限

		UserResourcesDto userResourcesDto=new UserResourcesDto();
		userResourcesDto.setMerchantId(user.getMerchantId());
		ResponseList<Resources> responseList=merchantResourcesServiceFacade.findUserResources(userResourcesDto);
		
		RoleResourcesDto roleResourcesDto=new RoleResourcesDto();
		roleResourcesDto.setRoleId(Long.valueOf(roleId));
		roleResourcesDto.setMerchantId(user.getMerchantId());;
		ResponseList<RoleResources> authorizedList=roleResourcesServiceFacade.findByDto(roleResourcesDto);
		//组装Znodes
		List<ZNodes> list=new ArrayList<ZNodes>();
		if(responseList.isSuccess() && null!=responseList.getEntity()){
			for(Resources r : responseList.getEntity() ){
				ZNodes znode=new ZNodes();
				znode.setId(r.getResourcesCode());
				znode.setpId(r.getParentCode());
				znode.setName(r.getResourcesName());
				String chkDisabled="false";
				for(String rc : appResources){
					if(r.getResourcesCode().equals(rc)){
						chkDisabled="true";
						break;
					}
				}
				znode.setChkDisabled(chkDisabled);
				boolean flag=false;
				if(authorizedList.isSuccess() && null!=authorizedList.getEntity()){
					for(RoleResources rr : authorizedList.getEntity()){
						if(r.getResourcesCode().equals(rr.getResourcesCode())){
							flag=true;
							break;
						}
					}
				}
				znode.setChecked(String.valueOf(flag));
				list.add(znode);
			}
		}
		return list;
	}
	
	//查找移动端资源
	private List<String> getAppRoleResourceCodeList(Long merchantId,String roleId){
		UserResourcesDto userResourcesDto = new UserResourcesDto();
		userResourcesDto.setRoleId(roleId);
		userResourcesDto.setMerchantId(merchantId);
		userResourcesDto.setResourcesType("2");
		ResponseList<Resources> responseList = merchantResourcesServiceFacade.findRoleResources(userResourcesDto);
		List<String> list=new ArrayList<String>();
		if(responseList.isSuccess() && null!=responseList.getEntity()){
			for(Resources resources:responseList.getEntity()){
				list.add(resources.getResourcesCode());
			}
		}
		return list;
		
	}
	
	//查询系统资源
	@RequestMapping(value="saveAuthorized", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes saveAuthorized(String roleId,String aus,String dataAuthoritys){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:role:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		
        		//查找原移动端权限
        		List<String> oldRRCList=getAppRoleResourceCodeList(user.getMerchantId(),roleId);
        		
    			//1.删除角色权限
        		RoleResourcesDto roleResourcesDto=new RoleResourcesDto();
        		roleResourcesDto.setRoleId(Long.valueOf(roleId));
        		roleResourcesDto.setMerchantId(user.getMerchantId());
        		//排除掉非删除部分
        		StringBuffer appendSql=new StringBuffer(" and resources_code NOT IN (");
        		int index=0;
        		for(String rc : appResources){
        			if(index>0){
        				appendSql.append(",");
        			}
        			appendSql.append("'");
        			appendSql.append(rc);
        			appendSql.append("'");
        			index++;
				}
        		appendSql.append(")");
        		roleResourcesDto.setAppendSql(appendSql.toString());
        		Response<Integer> deleteResponse=roleResourcesServiceFacade.deleteByDto(roleResourcesDto);
        		if(!deleteResponse.isSuccess()){
        			ar.setFailMsg("操作失败");
					return ar;
        		}
        		//2.保持角色资源信息
        		Date now=new Date();
        		String[] auss=aus.split(",");
        		List<RoleResourcesDto> listRRD=new ArrayList<RoleResourcesDto>();
        		for(String au : auss){
        			if(StringUtils.isNotBlank(au)){
        				RoleResourcesDto urd=new RoleResourcesDto();
        				urd.setRoleId(Long.valueOf(roleId));
        				urd.setMerchantId(user.getMerchantId());
        				urd.setResourcesCode(au);
        				urd.setCreateUserId(user.getId());
        				urd.setUpdateTime(now);
        				urd.setDelFlag("0");
        				urd.setCreateTime(now);
        				listRRD.add(urd);
        			}
        		}
        		//批量保存角色权限
				if(null != listRRD && listRRD.size() > 0){
					roleResourcesServiceFacade.insertBatch(listRRD);
				}

        		//批量删除数据权限
        		RoleDataAuthorityDto roleDataAuthorityDto=new RoleDataAuthorityDto();
        		roleDataAuthorityDto.setMerchantId(user.getMerchantId());
        		roleDataAuthorityDto.setRoleId(Long.valueOf(roleId));
        		deleteResponse=roleDataAuthorityServiceFacade.deleteByDto(roleDataAuthorityDto);
        		if(!deleteResponse.isSuccess()){
        			ar.setFailMsg("操作失败");
					return ar;
        		}
        		//批量保存数据权限
        		List<RoleDataAuthorityDto> listRDAD=new ArrayList<RoleDataAuthorityDto>();
        		String[] dataAuthorityArray=dataAuthoritys.split(",");
        		if(null != dataAuthorityArray && dataAuthorityArray.length > 0){
					for(String dataAuthority : dataAuthorityArray){
						String[] selectValue=dataAuthority.split(":");
						if(selectValue.length<=0)continue;
						RoleDataAuthorityDto dto=new RoleDataAuthorityDto();
						dto.setMerchantId(user.getMerchantId());
						dto.setResourcesCode(selectValue[0]);
						dto.setAuthorityValue(selectValue[1]);
						dto.setRoleId(Long.valueOf(roleId));
						dto.setCreateUserId(user.getId());
						dto.setDelFlag("0");
						dto.setUpdateUserId(user.getId());
						dto.setUpdateTime(now);
						dto.setCreateTime(now);
						listRDAD.add(dto);
					}
				}
        		roleDataAuthorityServiceFacade.insertByBatch(listRDAD);
        		//删缓角色缓存
        		removeResourcesCache(roleId);
        		//查找现移动端权限
        		List<String> newRRCList=getAppRoleResourceCodeList(user.getMerchantId(),roleId);
        		//如果两个集合值不一样，则需写入重新登陆标示
        		if(!CollectionUtils.isEqualCollection(oldRRCList, newRRCList)){
        			//写入重新登陆标示，app账号需要重新登陆
        			userTokenServiceFacade.addReLogin(roleId);
        		}
        		ar.setSucceedMsg("保存成功");
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
	}
	
	
}
